﻿using BusinessEntity;
using BusinessEntity.xmglQuerryEntity;
using BusinessRule;
using learun.util;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Nacos.AspNetCore;
using Newtonsoft.Json.Linq;
using ProjectManApi.Extensions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace ProjectManApi.Controllers.xmgl
{
    public class ProHeTongController : MvcControllerBase
    {
        private readonly INacosServerManager _serverManager;
        public ProHeTongController(INacosServerManager serverManager) : base(serverManager)
        {
            _serverManager = serverManager;
        }

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> ExportConList(dynamic expjson)
        {

            JObject job = (JObject)expjson;

            List<string> ids = new List<string>();
            List<ColumnModel> cols = new List<ColumnModel>();

            if (null != job["ids"])
                ids = job["ids"].ToObject<string[]>().ToList();

            if (null != job["cols"])
                cols = job["cols"].ToObject<ColumnModel[]>().ToList();

            return File(await CProTZJHRule.GetExportList(ids, cols, BaseEditPower.TableName.合同, "合同列表"), "application/ms-excel", "合同列表.xls");
            //return File(await ProHeTongRule.GetExportList(ids, cols), "application/ms-excel", "合同列表.xls");
        }


        #region 合同变更申请
        [HttpGet]
        //[AllowAnonymous]
        //string formCode, string xmid, string htmc, string xmmc, string htid, string htbh, string dxmc, string htlx, string cgmc, string zbfs, string ccode, string status, DateTime? begindate, DateTime? enddate, string current = "1", string size = "20", string sort = "desc", string column = "id"
        public async Task<IActionResult> GetHTBGSQLogIndexList([FromQuery] ProHeTongBGSQQuerry querry)
        {
            try
            {
                //ProHeTongBGSQQuerry querry = new ProHeTongBGSQQuerry();
                ////基础属性
                //querry.size = CommonHelper.ParseInt(size);
                //querry.current = CommonHelper.ParseInt(current);
                //querry.sort = sort;
                //querry.column = column;


                //querry.htmc = htmc;
                //querry.htlx = htlx;

                //querry.cgmc = cgmc;
                //querry.zbfs = zbfs;

                //querry.htbh = htbh;

                //querry.htid = htid;
                //querry.xmmc = xmmc;
                //querry.dxmc = dxmc;
                //querry.status = status;
                //querry.begindate = begindate;
                //querry.enddate = enddate;

                //querry.ccode = ccode;

                //querry.xmid = xmid;

                //(DataTable, int) SelectTable = await ProHeTongRule.GetHTIndexList(querry, await GetDepId());//GetUserId()

                (IEnumerable<dynamic>, int) SelectTable = await ProHeTongRule.GetHTBGSQLogIndexList(querry, await GetDepId());


                List<string> list = new List<string>();
                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.id;
                    list.Add(id);
                }

                List<JavaApi.SPSDataItem> spitems = await JavaApi.GetSPStatusJavaAPI(querry.formCode, GetUserAccount(), list, await GetICApiInfo());
                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.id;
                    var spstatus = spitems.Where(ii => ii.businessId == id).FirstOrDefault();

                    item.panguData = GetPanGudData(spstatus, item.spstatus);
                }

                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;
                return Success(pa);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="tid"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetHTBGSQAllInfo(string tid)
        {
            try
            {
                var SelectTable = await ProHeTongRule.GetHTBGSQAllInfo(tid);

                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }


        /// <summary>
        /// 插入修改
        /// </summary>
        /// <param name="htjson"></param>
        /// <returns></returns>
        [HttpPost]
        //[AllowAnonymous]
        public async Task<IActionResult> InsertCProContractBGSQ(dynamic htjson)
        {
            string strope = "add";
            CProContractbglog ht = new CProContractbglog();
            //CProContract tzjhnd = new CProTZJHND();

            //合同甲方
            CProContractSF htjf = new CProContractSF();
            //三方
            List<CProContractSF> htsf = new List<CProContractSF>();
            //收款账号
            List<BConstructionUnitsYH> htskzh = new List<BConstructionUnitsYH>();
            //付款计划
            List<CProConFKJH> htfkjh = new List<CProConFKJH>();
            //付款保证金
            List<CProConBZJ> htbzj = new List<CProConBZJ>();
            //负责人
            List<CProConFuZeRen> htfzr = new List<CProConFuZeRen>();
            //附件
            FileUploadent filecodes = new FileUploadent();
            try
            {
                JObject job = (JObject)htjson;

                //获取方法
                strope = htjson.ope;
                strope = strope.ToLower();

                //获取实体类 这样复杂类型不用定义实体类
                if (null != job["ht"])
                    ht = job["ht"].ToObject<CProContractbglog>();

                if (null != job["htjf"])
                    htjf = job["htjf"].ToObject<CProContractSF>();

                if (null != job["htsf"])
                    htsf = job["htsf"].ToObject<CProContractSF[]>().ToList();

                if (null != job["htskzh"])
                    htskzh = job["htskzh"].ToObject<BConstructionUnitsYH[]>().ToList();

                if (null != job["htfkjh"])
                    htfkjh = job["htfkjh"].ToObject<CProConFKJH[]>().ToList();

                if (null != job["htbzj"])
                    htbzj = job["htbzj"].ToObject<CProConBZJ[]>().ToList();

                if (null != job["htfzr"])
                    htfzr = job["htfzr"].ToObject<CProConFuZeRen[]>().ToList();

                //接收附件列表
                if (null != job["apiargs"])
                    filecodes = job["apiargs"].ToObject<FileUploadent>();

                if (strope != "add" && strope != "edit" && strope != "del" && strope != "submit")
                {
                    return Fail("参数ope 不合法");
                }

            }
            catch (Exception ex)
            {
                return Fail("参数转换出错：" + ex.Message);
            }

            try
            {

                //判断是否购买项目管理模块
                //_logger.Debug("是否购买项目管理模块");
                //string stradmin = ConfigHelper.GetAppSettings("ServerOp:SerAdmin");
                //bool exists = await XMListRule.sfgmmk(await GetICApiInfo(stradmin));
                //_logger.Debug("是否购买项目管理模块：" + exists);

                //合同编号也给了默认值
                //if (string.IsNullOrEmpty(ht.htbh))
                //{
                //    dynamic DCcode = await GetHTDic(ht.dxid, ht.htlx);
                //    ht.htbh = await JavaApi.BusinessBMJavaAPI(BaseEditPower.listTableName[BaseEditPower.TableName.合同.ToString()], Newtonsoft.Json.JsonConvert.SerializeObject(DCcode), await GetICApiInfo());
                //}

                if (string.IsNullOrEmpty(ht.htid))
                {
                    return Fail("合同主键htid不能为空");
                }

                //if (string.IsNullOrEmpty(ht.htbh))
                //{
                //    return Fail("合同编号不能为空");
                //}

                //if (string.IsNullOrEmpty(ht.dxid))
                //{
                //    CProContract xzhte = await TranstionRule.FindEntity<CProContract>(new { id = ht.htid });
                //    ht.dxid = xzhte.dxid;
                //}

                if (string.IsNullOrEmpty(ht.jf))
                {
                    return Fail("合同甲方不能为空");
                }
                if (string.IsNullOrEmpty(ht.yf))
                {
                    return Fail("合同乙方不能为空");
                }
                if (ht.htje == 0)
                {
                    return Fail("合同金额不能为空");
                }

                string strlsope = strope;
                if (strope == "submit")
                {
                    if (string.IsNullOrEmpty(ht.id))//完成新增
                    {
                        strope = "add";
                    }
                    else
                    {
                        CProContractbglog jhe = await TranstionRule.FindEntityByKey<CProContractbglog>(ht.id);
                        if (null == jhe)
                        {
                            strope = "add";
                        }
                        else
                        {
                            strope = "edit";
                        }
                    }
                    ht.status = BaseEditPower.GetSPEnumValue("待审核");
                }


                if (strope == "add")
                {
                    //这里进行赋值
                    ht.id = CommonHelper.GetUniqueId().ToString();

                    if (null == ht.createdate)
                    {
                        ht.createdate = DateTime.Now;
                    }

                    ht.bgr = GetUserName();
                    ht.bgrq = DateTime.Now;

                    if (string.IsNullOrEmpty(ht.htbh))
                    {
                        CProContract hte = await TranstionRule.FindEntity<CProContract>(new { id = ht.htid });
                        if (null != hte)
                        {
                            ht.htbh = hte.htbh;
                        }
                    }

                    ////如果合同编号存在
                    //if (await BusinessRule.ProHeTongRule.GetHTIDExits(ht.htbh, ht.dxid))
                    //{
                    //    return Fail("保存失败，该合同编号已经存在合同信息");
                    //}

                    //if (exists)//如果购买了模块
                    //{
                    //    CProContract hte = await TranstionRule.FindEntity<CProContract>(new { dxid = ht.dxid });
                    //    if (null != hte)
                    //    {
                    //        return Fail("保存失败，该单项已经存在合同信息");
                    //    }
                    //}

                    if (strlsope != "submit")
                        ht.status = BaseEditPower.GetSPEnumValue("待提交");

                    //这里先绑定附件
                    await JavaApi.UploadFileJavaAPI(ht.id, filecodes, await GetICApiInfo());

                    bool bsp = true;
                    if (strlsope == "submit")
                    {
                        bsp = false;

                        var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.合同修改记录.ToString(), ht.id);

                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = ht.htbh, amount = ht.htje?.ToString(), content = "[项目合同]" + ht.htmc, deptName = GetUserDeptName() };

                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.合同修改记录.ToString(), ht.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(htjson), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);
                        //bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        //if (!bsp)
                        string strInstanceId = await JavaApi.startInstanceJavaAPIStr(spl, await GetICApiInfo());
                        ht.spl = strInstanceId;
                        if (strInstanceId.StartsWith("err"))
                        {
                            return Fail("提交失败，启动工作流异常");
                        }
                    }
                    //新增合同
                    await BusinessRule.ProHeTongRule.InsertCProContractBGSQ(ht, htjf, htsf, htskzh, htfkjh, htbzj, htfzr, strope);
                }
                else if (strope == "edit")
                {
                    if (string.IsNullOrEmpty(ht.id))
                    {
                        return Fail("合同id不能为空");
                    }

                    //if (await BusinessRule.ProHeTongRule.GetHTIDExits(ht.htbh, ht.dxid))
                    //{
                    //    return Fail("保存失败，该合同编号已经存在合同信息");
                    //}

                    //这里先绑定附件
                    await JavaApi.UploadFileJavaAPI(ht.id, filecodes, await GetICApiInfo());

                    bool bsp = true;
                    if (strlsope == "submit")
                    {
                        bsp = false;

                        //CProContract jhe = await TranstionRule.FindEntityByKey<CProContract>(ht.id);
                        //if (null == jhe)
                        //{
                        //    return Fail("根据id未检索到合同信息");
                        //}

                        var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.合同修改记录.ToString(), ht.id);

                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = ht.htbh, amount = ht.htje?.ToString(), content = "[项目合同]" + ht.htmc, deptName = GetUserDeptName() };
                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.合同修改记录.ToString(), ht.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(htjson), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);

                        //bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        //if (!bsp)
                        string strInstanceId = await JavaApi.startInstanceJavaAPIStr(spl, await GetICApiInfo());
                        ht.spl = strInstanceId;
                        if (strInstanceId.StartsWith("err"))
                        {
                            return Fail("提交失败，启动工作流异常");
                        }
                    }
                    //新增合同
                    await BusinessRule.ProHeTongRule.InsertCProContractBGSQ(ht, htjf, htsf, htskzh, htfkjh, htbzj, htfzr, strope);
                }


                //_logger.Error(htjson.ToJson() + " 保存合同成功");
                return Success("成功");
            }
            catch (Exception ex)
            {

                _logger.Error(ex.Message);

                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 根据id删除多条数据
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> DeleteCProContractBGSQMulti(Root ids)
        {
            try
            {
                foreach (BaseDeleteMulti idm in ids.ids)
                {
                    if (!await BaseEditPower.GetEditPower(idm.id, BaseEditPower.TableName.合同修改记录))
                    {
                        throw new Exception("请确认数据权限");
                    }
                }

                await BusinessRule.ProHeTongRule.DeleteCProContractBGSQMulti(ids);

                return Success("成功");
            }
            catch (Exception ex)
            {
                //_logger.Error(ids.ToJson() + "||" + ex.Message);
                return Fail(ex.Message);
            }
        }
        #endregion

        #region 合同列表（过滤条件：项目名称、合同编号、合同名称、状态、合同起始日期、合同截止日期）ProHeTongLists.aspx、合同新增修改、合同删除、合同甲方、合同乙方、项目节点ProHeTongAdd.aspx
        /// <summary>
        /// 选择合同列表
        /// </summary>
        /// <param name="xmmc"></param>
        /// <param name="htid"></param>
        /// <param name="dxmc"></param>
        /// <param name="status"></param>
        /// <param name="begindate"></param>
        /// <param name="enddate"></param>
        /// <param name="current"></param>
        /// <param name="size"></param>
        /// <param name="sort"></param>
        /// <param name="column"></param>
        /// <returns></returns>
        [HttpGet]
        //string htmc, string xmmc, string htid, string dxmc, string htbh, string current = "1", string size = "20", string sort = "desc", string column = "id"
        public async Task<IActionResult> GetXZHTIndexList([FromQuery] ProHeTongQuerry querry)
        {
            try
            {
                //ProHeTongQuerry querry = new ProHeTongQuerry();
                ////基础属性
                //querry.size = CommonHelper.ParseInt(size);
                //querry.current = CommonHelper.ParseInt(current);
                //querry.sort = sort;
                //querry.column = column;


                //querry.htmc = htmc;

                //querry.htbh = htbh;
                //querry.htid = htid;
                //querry.xmmc = xmmc;
                //querry.dxmc = dxmc;

                (IEnumerable<dynamic>, int) SelectTable = await ProHeTongRule.GetXZHTIndexList(querry, await GetDepId());



                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;
                return Success(pa);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 合同列表
        /// </summary>
        /// <param name="xmmc"></param>
        /// <param name="htid"></param>
        /// <param name="dxmc"></param>
        /// <param name="status"></param>
        /// <param name="begindate"></param>
        /// <param name="enddate"></param>
        /// <param name="current"></param>
        /// <param name="size"></param>
        /// <param name="sort"></param>
        /// <param name="column"></param>
        /// <returns></returns>
        [HttpGet]
        //[AllowAnonymous]
        public async Task<IActionResult> GetHTIndexList(string formCode, string xmid, string htmc, string xmmc, string htid, string htbh, string dxmc, string htlx, string cgmc, string zbfs, string ccode, string status, DateTime? begindate, DateTime? enddate, string current = "1", string size = "20", string sort = "desc", string column = "id")
        {
            try
            {
                ProHeTongQuerry querry = new ProHeTongQuerry();
                //基础属性
                querry.size = CommonHelper.ParseInt(size);
                querry.current = CommonHelper.ParseInt(current);
                querry.sort = sort;
                querry.column = column;


                querry.htmc = htmc;
                querry.htlx = htlx;

                querry.cgmc = cgmc;
                querry.zbfs = zbfs;

                querry.htbh = htbh;

                querry.htid = htid;
                querry.xmmc = xmmc;
                querry.dxmc = dxmc;
                querry.status = status;
                querry.begindate = begindate;
                querry.enddate = enddate;

                querry.ccode = ccode;

                querry.xmid = xmid;

                //(DataTable, int) SelectTable = await ProHeTongRule.GetHTIndexList(querry, await GetDepId());//GetUserId()

                (IEnumerable<dynamic>, int) SelectTable = await ProHeTongRule.GetHTIndexList(querry, await GetDepId());


                List<string> list = new List<string>();
                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.id;
                    list.Add(id);
                }

                List<JavaApi.SPSDataItem> spitems = await JavaApi.GetSPStatusJavaAPI(formCode, GetUserAccount(), list, await GetICApiInfo());
                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.id;
                    var spstatus = spitems.Where(ii => ii.businessId == id).FirstOrDefault();

                    item.panguData = GetPanGudData(spstatus, item.spstatus);
                }

                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;
                return Success(pa);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 根据合同id获取单条合同信息
        /// </summary>
        /// <param name="tid"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetHTXXById(string tid)
        {
            try
            {
                var SelectTable = await ProHeTongRule.GetHTById(tid);

                //SelectTable.
                //if (SelectTable.ToList()[0].htid = "")
                //{
                //    SelectTable.ToList()[0].htid = "111";
                //}

                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tid"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetHTAllInfo(string tid)
        {
            try
            {
                var SelectTable = await ProHeTongRule.GetHTAllInfo(tid);

                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        protected async Task<dynamic> GetHTDic(string dxid, string htlx)
        {
            string strdxid = dxid;

            string zjxz = "";
            string tid = htlx;
            string bid = "";

            string strsql = @"select zjly,(case when REPLACE(ISNULL(zjly,''),'财政','') = ISNULL(zjly,'') then '0' else '1' end)zid,
xmflname,departid,(select remark from BDicInfo
where type = '项目类型' and xmflname = tname
)tid,buildunit,(select bmbh from BGlbmInfo where bmmc = buildunit)bid from CProManage
where id in (select xmid from CProManageLX where id = '" + strdxid + "')";

            DataTable dts = await TranstionRule.ProcessSql(strsql);
            for (int i = 0; i < dts.Rows.Count; i++)
            {
                zjxz = dts.Rows[i]["zid"].ToString() == "1" ? "CZ" : "JY";
                //tid = dts.Rows[i]["xmflname"].ToString();
                bid = dts.Rows[i]["departid"].ToString();
            }

            _logger.Warn("11");
            string tname = await GetDicJavaAPI("contract-type", tid);
            _logger.Warn("12");
            string bname = "";
            var dwinfo = await GetDepInfoSig(bid, "project_permission");
            _logger.Warn("13");
            if (null != dwinfo)
                bname = dwinfo.mnemonicCode;
            _logger.Warn("14");
            dynamic DCcode = new ExpandoObject();
            DCcode.zcode = zjxz;//资金来源
            DCcode.tcode = tname;//项目类型code
            DCcode.bcode = bname;//建设单位code
            _logger.Warn("15");

            return DCcode;
        }

        /// <summary>
        /// 插入修改
        /// </summary>
        /// <param name="htjson"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> InsertCProContract(dynamic htjson)
        {
            string strope = "add";
            CProContract ht = new CProContract();
            //CProContract tzjhnd = new CProTZJHND();

            //合同甲方
            CProContractSF htjf = new CProContractSF();
            //三方
            List<CProContractSF> htsf = new List<CProContractSF>();
            //收款账号
            List<BConstructionUnitsYH> htskzh = new List<BConstructionUnitsYH>();
            //付款计划
            List<CProConFKJH> htfkjh = new List<CProConFKJH>();
            //付款保证金
            List<CProConBZJ> htbzj = new List<CProConBZJ>();
            //负责人
            List<CProConFuZeRen> htfzr = new List<CProConFuZeRen>();
            //附件
            FileUploadent filecodes = new FileUploadent();
            try
            {
                JObject job = (JObject)htjson;

                //获取方法
                strope = htjson.ope;
                strope = strope.ToLower();

                //获取实体类 这样复杂类型不用定义实体类
                if (null != job["ht"])
                    ht = job["ht"].ToObject<CProContract>();

                if (null != job["htjf"])
                    htjf = job["htjf"].ToObject<CProContractSF>();

                if (null != job["htsf"])
                    htsf = job["htsf"].ToObject<CProContractSF[]>().ToList();

                if (null != job["htskzh"])
                    htskzh = job["htskzh"].ToObject<BConstructionUnitsYH[]>().ToList();

                if (null != job["htfkjh"])
                    htfkjh = job["htfkjh"].ToObject<CProConFKJH[]>().ToList();

                if (null != job["htbzj"])
                    htbzj = job["htbzj"].ToObject<CProConBZJ[]>().ToList();

                if (null != job["htfzr"])
                    htfzr = job["htfzr"].ToObject<CProConFuZeRen[]>().ToList();

                //接收附件列表
                if (null != job["apiargs"])
                    filecodes = job["apiargs"].ToObject<FileUploadent>();

                if (strope != "add" && strope != "edit" && strope != "del" && strope != "submit")
                {
                    return Fail("参数ope 不合法");
                }

            }
            catch (Exception ex)
            {
                return Fail("参数转换出错：" + ex.Message);
            }

            try
            {

                //判断是否购买项目管理模块
                _logger.Debug("是否购买项目管理模块");
                string stradmin = ConfigHelper.GetAppSettings("ServerOp:SerAdmin");
                bool exists = await XMListRule.sfgmmk(await GetICApiInfo(stradmin));
                _logger.Debug("是否购买项目管理模块：" + exists);

                //合同编号也给了默认值
                if (string.IsNullOrEmpty(ht.htbh))
                {
                    if (string.IsNullOrEmpty(ht.htlx))
                    {
                        return Fail("合同信息中合同类型不能为空");
                    }

                    _logger.Warn("1");
                    dynamic DCcode = await GetHTDic(ht.dxid, ht.htlx);
                    _logger.Warn("2");
                    ht.htbh = await JavaApi.BusinessBMJavaAPI(BaseEditPower.listTableName[BaseEditPower.TableName.合同.ToString()], Newtonsoft.Json.JsonConvert.SerializeObject(DCcode), await GetICApiInfo());

                    //await BusinessRule.Assets.CreateZCDM("XM", "HTBH");
                }

                if (string.IsNullOrEmpty(ht.htbh))
                {
                    return Fail("合同编号不能为空");
                }



                if (exists)//如果购买了模块
                {
                    if (string.IsNullOrEmpty(ht.dxid))
                    {
                        return Fail("标段编号不能为空");
                    }


                    string strlx = await CProTZJHRule.GetFunGLListBylxEunm(BaseEditPower.JumpModule.合同金额限制.ToString());

                    if (strlx == "1")
                    {
                        CProZB jhe = await TranstionRule.FindEntity<CProZB>(new { dxid = ht.dxid, lx = "zb" });
                        if (null != jhe)
                        {
                            if (jhe.zbje != null && jhe.zbje != 0 && ht.htje != jhe.zbje)
                            {
                                return Fail("合同金额和中标金额不相等.");
                            }
                        }
                    }

                }
                else//没采购
                {
                    if (string.IsNullOrEmpty(ht.htxmmc))
                    {
                        return Fail("合同信息中项目名称htxmmc不能为空");
                    }
                    if (string.IsNullOrEmpty(ht.htdxmc))
                    {
                        return Fail("合同信息中单项名称dxmc不能为空");
                    }
                    if (string.IsNullOrEmpty(ht.gsid))
                    {
                        return Fail("合同信息中权限gsid不能为空");
                    }
                }

                if (string.IsNullOrEmpty(ht.jf))
                {
                    return Fail("合同甲方不能为空");
                }
                if (string.IsNullOrEmpty(ht.yf))
                {
                    return Fail("合同乙方不能为空");
                }
                if (ht.htje == 0)
                {
                    return Fail("合同金额不能为空");
                }

                string strlsope = strope;
                if (strope == "submit")
                {
                    if (string.IsNullOrEmpty(ht.id))//完成新增
                    {
                        strope = "add";
                    }
                    else
                    {
                        CProContract jhe = await TranstionRule.FindEntityByKey<CProContract>(ht.id);
                        if (null == jhe)
                        {
                            strope = "add";
                        }
                        else
                        {
                            strope = "edit";
                        }
                    }
                    ht.status = BaseEditPower.GetSPEnumValue("待审核");
                }


                if (strope == "add")
                {
                    //这里进行赋值
                    ht.id = CommonHelper.GetUniqueId().ToString();
                    //ht.createuser = GetUserId();
                    //ht.gsid = GetUserDeptid();//获取部门id

                    if (null == ht.createdate)
                    {
                        ht.createdate = DateTime.Now;
                    }



                    //如果合同编号存在
                    if (await BusinessRule.ProHeTongRule.GetHTIDExits(ht.htbh, ht.dxid))
                    {
                        return Fail("保存失败，该合同编号已经存在合同信息");
                    }

                    if (exists)//如果购买了模块
                    {
                        CProContract hte = await TranstionRule.FindEntity<CProContract>(new { dxid = ht.dxid });
                        if (null != hte)
                        {
                            return Fail("保存失败，该单项已经存在合同信息");
                        }
                    }

                    if (strlsope != "submit")
                        ht.status = BaseEditPower.GetSPEnumValue("待提交");

                    //这里先绑定附件
                    await JavaApi.UploadFileJavaAPI(ht.id, filecodes, await GetICApiInfo());

                    bool bsp = true;
                    if (strlsope == "submit")
                    {
                        bsp = false;

                        var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.合同.ToString(), ht.id);

                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = ht.htbh, amount = ht.htje?.ToString(), content = "[项目合同]" + ht.htmc, deptName = GetUserDeptName() };

                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.合同.ToString(), ht.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(htjson), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);
                        //bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        //if (!bsp)
                        string strInstanceId = await JavaApi.startInstanceJavaAPIStr(spl, await GetICApiInfo());
                        ht.spl = strInstanceId;
                        if (strInstanceId.StartsWith("err"))
                        {
                            return Fail("提交失败，启动工作流异常");
                        }
                    }
                    //新增合同
                    await BusinessRule.ProHeTongRule.InsertCProContract(ht, htjf, htsf, htskzh, htfkjh, htbzj, htfzr, strope);
                }
                else if (strope == "edit")
                {
                    if (string.IsNullOrEmpty(ht.id))
                    {
                        return Fail("合同id不能为空");
                    }

                    if (await BusinessRule.ProHeTongRule.GetHTIDExits(ht.htbh, ht.dxid))
                    {
                        return Fail("保存失败，该合同编号已经存在合同信息");
                    }

                    //这里先绑定附件
                    await JavaApi.UploadFileJavaAPI(ht.id, filecodes, await GetICApiInfo());

                    bool bsp = true;
                    if (strlsope == "submit")
                    {
                        bsp = false;

                        //CProContract jhe = await TranstionRule.FindEntityByKey<CProContract>(ht.id);
                        //if (null == jhe)
                        //{
                        //    return Fail("根据id未检索到合同信息");
                        //}

                        var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.合同.ToString(), ht.id);

                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = ht.htbh, amount = ht.htje?.ToString(), content = "[项目合同]" + ht.htmc, deptName = GetUserDeptName() };
                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.合同.ToString(), ht.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(htjson), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);

                        //bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        //if (!bsp)
                        string strInstanceId = await JavaApi.startInstanceJavaAPIStr(spl, await GetICApiInfo());
                        ht.spl = strInstanceId;
                        if (strInstanceId.StartsWith("err"))
                        {
                            return Fail("提交失败，启动工作流异常");
                        }
                    }
                    //新增合同
                    await BusinessRule.ProHeTongRule.InsertCProContract(ht, htjf, htsf, htskzh, htfkjh, htbzj, htfzr, strope);
                }


                //_logger.Error(htjson.ToJson() + " 保存合同成功");
                return Success("成功");
            }
            catch (Exception ex)
            {

                _logger.Error(ex.Message);

                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 插入修改
        /// </summary>
        /// <param name="ht"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> InsertCProContractby(CProContract ht)
        {
            try
            {
                //_logger.Debug("接收:" + ht.ToJson());
                if (string.IsNullOrEmpty(ht.htbh))
                {
                    return Fail("合同编号不能为空");
                }
                if (string.IsNullOrEmpty(ht.dxid))
                {
                    return Fail("标段编号不能为空");
                }
                if (string.IsNullOrEmpty(ht.jf))
                {
                    return Fail("合同甲方不能为空");
                }
                if (string.IsNullOrEmpty(ht.yf))
                {
                    return Fail("合同乙方不能为空");
                }
                if (ht.htje == 0)
                {
                    return Fail("合同金额不能为空");
                }


                await BusinessRule.ProHeTongRule.InsertCProContract(ht, GetUserId());

                //_logger.Debug("成功");
                return Success("成功");
            }
            catch (Exception ex)
            {

                //_logger.Error(ex.Message);

                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 根据id删除多条数据
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> DeleteCProContractMulti(Root ids)
        {
            try
            {
                foreach (BaseDeleteMulti idm in ids.ids)
                {
                    if (!await BaseEditPower.GetEditPower(idm.id, BaseEditPower.TableName.合同))
                    {
                        throw new Exception("请确认数据权限");
                    }
                    string sql = "select ISNULL(sqje,0.00)sqje from CProFKSQ where htid = '" + idm.id + "'";
                    DataTable table = await TranstionRule.ProcessSql(sql);
                    string str2 = "0";
                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        str2 = table.Rows[i]["sqje"].ToString();
                    }
                    if (str2.ToDecimal() != 0)
                    {
                        throw new Exception("已有付款申请，不能删除");
                    }
                }

                await BusinessRule.ProHeTongRule.DeleteCProContractMulti(ids);

                return Success("成功");
            }
            catch (Exception ex)
            {
                //_logger.Error(ids.ToJson() + "||" + ex.Message);
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 合同甲方
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetHTJF(string name)
        {
            try
            {
                var SelectTable = await ProHeTongRule.GetHTJF(name);

                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetHTJFNew(string name)
        {
            try
            {
                var SelectTable = await GetDepInfoTree("unit", name, "project_permission");

                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 合同乙方
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpGet]
        //[AllowAnonymous]
        public async Task<IActionResult> GetHTYF(string name, string current = "1", string size = "20", string sort = "desc", string column = "id")
        {
            try
            {
                var SelectTable = await ProHeTongRule.GetHTYF(name, current, size, sort, column);

                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        ///// <summary>
        ///// 合同乙方
        ///// </summary>
        ///// <param name="name"></param>
        ///// <returns></returns>
        //[HttpGet]
        //[AllowAnonymous]
        //public async Task<IActionResult> GetHTYF(string name)
        //{
        //    try
        //    {
        //        var SelectTable = await ProHeTongRule.GetHTYF(name);

        //        return Success(SelectTable);
        //    }
        //    catch (Exception ex)
        //    {
        //        return Fail(ex.Message);
        //    }
        //}

        /// <summary>
        /// 根据乙方名称获取历史
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetHTSKYHByYF(string name)
        {
            try
            {
                var SelectTable = await ProHeTongRule.GetHTSKYHByYF(name);

                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetHTBZJList(string tid)
        {
            try
            {
                var SelectTable = await ProHeTongRule.GetHTBZJList(tid);

                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }
        #endregion

        #region 合同附属查询，工资卡，付款计划
        /// <summary>
        /// 获取付款计划列表
        /// </summary>
        /// <param name="htid"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetHTFKJH(string htid)
        {
            try
            {
                var SelectTable = await ProHeTongRule.GetHTFKJH(htid);

                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 获取农民工收款银行信息列表  付款申请时选择
        /// </summary>
        /// <param name="htid"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetHTNMGSKYHByhtid(string htid)
        {
            try
            {
                var SelectTable = await ProHeTongRule.GetHTNMGSKYHN(htid);

                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 获取收款银行信息列表  付款申请时选择
        /// </summary>
        /// <param name="htid"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetHTSKYHByhtid(string htid)
        {
            try
            {
                var SelectTable = await ProHeTongRule.GetHTSKYHN(htid, "");

                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 获取收款银行信息列表  付款申请时选择
        /// </summary>
        /// <param name="htid"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetHTSKYH(string htid, string sqid)
        {
            try
            {
                //sqid = sqid== "undefined"?""

                var SelectTable = await ProHeTongRule.GetHTSKYHN(htid, sqid);

                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 获取相关联系人信息列表  项目送审时显示
        /// </summary>
        /// <param name="htid"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetHTFuZeRen(string htid)
        {
            try
            {
                var SelectTable = await ProHeTongRule.GetHTFuZeRen(htid);

                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }
        #endregion

        #region 合同变更

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> ExportConBGList(dynamic expjson)
        {

            JObject job = (JObject)expjson;

            List<string> ids = new List<string>();
            List<ColumnModel> cols = new List<ColumnModel>();

            if (null != job["ids"])
                ids = job["ids"].ToObject<string[]>().ToList();

            if (null != job["cols"])
                cols = job["cols"].ToObject<ColumnModel[]>().ToList();

            return File(await CProTZJHRule.GetExportList(ids, cols, BaseEditPower.TableName.合同变更, "合同变更列表"), "application/ms-excel", "合同列表.xls");
        }

        /// <summary>
        /// 项目变更列表
        /// </summary>
        /// <param name="xmmc"></param>
        /// <param name="jsdw"></param>
        /// <param name="begindate"></param>
        /// <param name="enddate"></param>
        /// <param name="current"></param>
        /// <param name="size"></param>
        /// <param name="sort"></param>
        /// <param name="column"></param>
        /// <returns></returns>
        [HttpGet]
        //[Authorize(Policy = "TestPolicy")]
        //[AllowAnonymous]
        //bgmc   bglx
        public async Task<IActionResult> GetHTBGList(string formCode, string xmid, string xmmc, string jsdw, string status, string bgmc, string bglx, DateTime? begindate, DateTime? enddate, string current = "1", string size = "20", string sort = "desc", string column = "id")
        {
            try
            {
                CProConBGQuerry querry = new CProConBGQuerry();
                //基础属性
                querry.size = CommonHelper.ParseInt(size);
                querry.current = CommonHelper.ParseInt(current);
                querry.sort = sort;
                querry.column = column;

                querry.bgmc = bgmc;
                querry.bglx = bglx;

                querry.Xmmc = xmmc;
                querry.Jsdw = jsdw;
                querry.Status = status;
                querry.Begindate = begindate;
                querry.Enddate = enddate;

                querry.xmid = xmid;



                (IEnumerable<dynamic>, int) SelectTable = await ProHeTongRule.GetHTBGList(querry, await GetDepId());//GetUserId()

                List<string> list = new List<string>();
                foreach (dynamic item in SelectTable.Item1)
                {
                    //这里是id
                    string id = item.id;
                    list.Add(id);
                }

                //审批流
                _logger.Debug(list.ToJson());
                List<JavaApi.SPSDataItem> spitems = await JavaApi.GetSPStatusJavaAPI(formCode, GetUserAccount(), list, await GetICApiInfo());
                _logger.Debug(spitems.ToJson());

                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.id;
                    var spstatus = spitems.Where(ii => ii.businessId == id).FirstOrDefault();

                    item.panguData = GetPanGudData(spstatus, item.spstatus);

                    //if (null != spstatus)
                    //    item.panguData = GetPanGudData(spstatus, item.spstatus);
                    //else
                    //    item.panguData = new JavaApi.panguData() { reviewStatus = item.spstatus };
                }



                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;
                return Success(pa);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 合同变更列表
        /// </summary>
        /// <param name="htid"></param>
        /// <returns></returns>
        [HttpGet]
        //[AllowAnonymous]
        public async Task<IActionResult> GetHTBGListByhtid(string htid)
        {
            try
            {
                var SelectTable = await ProHeTongRule.GetHTBGListByhtid(htid);

                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }


        /// <summary>
        /// 单条合同变更
        /// </summary>
        /// <param name="bgid"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetHTBGById(string bgid)
        {
            try
            {
                var SelectTable = await ProHeTongRule.GetHTBGByid(bgid);



                //List<dynamic> ListPerson = SelectTable.ToJson().ToObject<List<dynamic>>();
                foreach (var item in SelectTable)
                {
                    string strhtid = item.htid;
                    var vhtxx = (await ProHeTongRule.GetHTByIdSig(strhtid));
                    item.htxx = vhtxx;

                    string strdesid = item.did;
                    if (!string.IsNullOrEmpty(strdesid))
                    {
                        var desxx = (await ProHeTongRule.GetHTBGDesignByid(strdesid));
                        item.desxx = desxx;
                    }
                }


                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 单条合同变更
        /// </summary>
        /// <param name="bgid"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetHTBGJEById(string htid,string bgid)
        {
            try
            {
                var SelectTable = await ProHeTongRule.GetHTBGJEById(htid, bgid);

                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }


        /// <summary>
        /// 修改合同变更
        /// </summary>
        /// <param name="htbgjson"></param>
        /// <param name="strlx"></param>
        /// <returns></returns>
        [HttpPost]
        //[AllowAnonymous]
        public async Task<IActionResult> InsertCProConBG(dynamic htbgjson)//, string strlx = "xxx"
        {
            string strope = "add";
            CProConBG htbg = new CProConBG();

            //添加附件上传
            FileUploadent filecodes = new FileUploadent();
            try
            {
                JObject job = (JObject)htbgjson;

                //获取方法
                strope = htbgjson.ope ?? "";
                strope = strope.ToLower();

                //获取实体类 这样复杂类型不用定义实体类
                htbg = job["htbg"].ToObject<CProConBG>();

                //if (null != job["tzxmids"])
                //    tzxmids = job["tzxmids"].ToObject<List<CProManageTZXM>>();

                //接收附件列表
                if (null != job["apiargs"])
                    filecodes = job["apiargs"].ToObject<FileUploadent>();


                if (strope != "add" && strope != "edit" && strope != "approved" && strope != "submit")
                {
                    return Fail("参数ope 不合法");
                }

            }
            catch (Exception ex)
            {
                return Fail("参数转换出错：" + ex.Message);
            }

            try
            {

                string strlsope = strope;
                if (strope == "submit")
                {
                    if (string.IsNullOrEmpty(htbg.id))//完成新增
                    {
                        strope = "add";
                    }
                    else
                    {
                        CProConBG jhe = await TranstionRule.FindEntityByKey<CProConBG>(htbg.id);
                        if (null == jhe)
                        {
                            strope = "add";
                        }
                        else
                        {
                            strope = "edit";
                        }
                    }
                    htbg.status = BaseEditPower.GetSPEnumValue("待审核");
                }

                if (strope == "add")
                {
                    if (string.IsNullOrEmpty(htbg.htid))
                    {
                        return Fail("变更关联的合同id不能为空");
                    }
                    if (htbg.sqje == 0)
                    {
                        return Fail("变更金额不能为空或零");
                    }

                    //新增合同变更编码
                    htbg.bgbm = await JavaApi.BusinessBMJavaAPI(BaseEditPower.listTableName[BaseEditPower.TableName.合同变更.ToString()], Newtonsoft.Json.JsonConvert.SerializeObject(htbgjson), await GetICApiInfo());
                    //await BusinessRule.Assets.CreateZCDM("XM", "HTBG");

                    //重新赋值一个新id
                    htbg.id = CommonHelper.GetUniqueId().ToString();
                    htbg.createuser = GetUserId();


                    //填报时间
                    htbg.tbsj = DateTime.Now;


                    if (strlsope != "submit")
                        htbg.status = BaseEditPower.GetSPEnumValue("待提交");

                    //这里先绑定附件
                    await JavaApi.UploadFileJavaAPI(htbg.id, filecodes, await GetICApiInfo());

                    bool bsp = true;
                    if (strlsope == "submit")
                    {
                        //dynamic dd = await ProHeTongRule.GetHTBGScale(htbg);
                        //htbgjson.bl = dd.bl;

                        htbgjson.bl = htbg.ljbgbl;

                        dynamic _dynamic = new ExpandoObject();
                        _dynamic.sqje = htbg.sqje;
                        _dynamic.bl = htbg.ljbgbl;

                        bsp = false;

                        var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.合同变更.ToString(), htbg.id);

                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = htbg.bgbm, amount = htbg.sqje?.ToString(), content = "[合同变更]" + htbg.bgmc, deptName = GetUserDeptName() };

                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.合同变更.ToString(), htbg.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(_dynamic), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);
                        //bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        //if (!bsp)
                        string strInstanceId = await JavaApi.startInstanceJavaAPIStr(spl, await GetICApiInfo());
                        htbg.spl = strInstanceId;
                        if (strInstanceId.StartsWith("err"))
                        {
                            return Fail("提交失败，启动工作流异常");
                        }
                    }

                    //新增投资计划
                    await ProHeTongRule.InsertHTBG(htbg, "add");


                }
                else if (strope == "edit")
                {
                    if (string.IsNullOrEmpty(htbg.id))
                    {
                        return Fail("需要修改的变更id不能为空");
                    }
                    if (string.IsNullOrEmpty(htbg.htid))
                    {
                        return Fail("变更关联的合同id不能为空");
                    }
                    if (htbg.sqje == 0)
                    {
                        return Fail("变更金额不能为空或零");
                    }

                    //这里先绑定附件
                    await JavaApi.UploadFileJavaAPI(htbg.id, filecodes, await GetICApiInfo());

                    bool bsp = true;
                    if (strlsope == "submit")
                    {

                        //dynamic dd = await ProHeTongRule.GetHTBGScale(htbg);
                        //htbgjson.bl = dd.bl;
                        //累计变更比例
                        htbgjson.bl = htbg.ljbgbl;

                        dynamic _dynamic = new ExpandoObject();
                        _dynamic.sqje = htbg.sqje;
                        _dynamic.bl = htbg.ljbgbl;

                        bsp = false;
                        CProConBG jhe = await TranstionRule.FindEntityByKey<CProConBG>(htbg.id);
                        if (null == jhe)
                        {
                            return Fail("根据id未检索到变更信息");
                        }

                        var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.合同变更.ToString(), htbg.id);

                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = jhe.bgbm, amount = htbg.sqje?.ToString(), content = "[合同变更]" + htbg.bgmc, deptName = GetUserDeptName() };
                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.合同变更.ToString(), htbg.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(_dynamic), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);
                        //bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        //if (!bsp)
                        string strInstanceId = await JavaApi.startInstanceJavaAPIStr(spl, await GetICApiInfo());
                        htbg.spl = strInstanceId;
                        if (strInstanceId.StartsWith("err"))
                        {
                            return Fail("提交失败，启动工作流异常");
                        }
                    }

                    //新增投资计划
                    await ProHeTongRule.InsertHTBG(htbg, "edit");
                }
                else if (strope == "approved")
                {
                    if (string.IsNullOrEmpty(htbg.id))
                    {
                        return Fail("合同变更编号不能为空");
                    }
                    if (htbg.bgsdje == 0)
                    {
                        return Fail("变更审定金额不能为空或零");
                    }

                    //获取概算的当前状态
                    CProConBG htBGe = await TranstionRule.FindEntityByKey<CProConBG>(htbg.id);
                    string strstatus = "";
                    if (null != htBGe)
                    {
                        strstatus = htBGe.status ?? "";
                    }

                    if (strstatus == "2")
                    {
                        //这里先绑定附件
                        await JavaApi.UploadFileJavaAPI(htbg.id, filecodes, await GetICApiInfo());

                        //新增投资计划
                        await ProHeTongRule.InsertHTBG(htbg, "edit");
                    }
                    else
                    {
                        return Fail("数据状态为" + strstatus + ",未审核完成");
                    }
                }


                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail("响应失败:" + ex.Message);
            }
        }

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> DeleteCProConBGMulti(Root ids)//
        {
            try
            {
                foreach (BaseDeleteMulti idm in ids.ids)
                {
                    if (string.IsNullOrEmpty(idm.id))
                    {
                        return Fail("需要删除的变更编号不能为空");
                    }

                    if (!await BaseEditPower.GetEditPower(idm.id, BaseEditPower.TableName.合同变更))
                    {
                        //throw new Exception("请确认数据权限");
                        return Fail("响应失败:请确认数据权限");
                    }
                }
            }
            catch (Exception ex)
            {
                return Fail("出错：" + ex.Message);
            }


            try
            {
                //新增投资计划
                if (await ProHeTongRule.DeleteHTBG(ids))
                {
                    return Success("成功");
                }
                else
                {
                    return Fail("影响行数为0");
                }

            }
            catch (Exception ex)
            {
                return Fail("响应失败:" + ex.Message);
            }
        }

        #endregion

        #region 合同变更协议

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> ExportConBGxyList(dynamic expjson)
        {

            JObject job = (JObject)expjson;

            List<string> ids = new List<string>();
            List<ColumnModel> cols = new List<ColumnModel>();

            if (null != job["ids"])
                ids = job["ids"].ToObject<string[]>().ToList();

            if (null != job["cols"])
                cols = job["cols"].ToObject<ColumnModel[]>().ToList();

            return File(await CProTZJHRule.GetExportList(ids, cols, BaseEditPower.TableName.变更协议, "合同变更协议列表"), "application/ms-excel", "合同列表.xls");
        }

        [HttpGet]
        //[AllowAnonymous]
        public async Task<IActionResult> GetHTBGXYList(string formCode, string xmmc, string dxmc, string htmc, string xymc, string status, string ccode, string dateRange, string current = "1", string size = "20", string sort = "desc", string column = "id")
        {
            try
            {
                dynamic querry = new ExpandoObject();
                //基础属性
                querry.size = size;
                querry.current = current;
                querry.sort = sort;
                querry.column = column;

                querry.xmmc = xmmc;
                querry.dxmc = dxmc;

                querry.htmc = htmc;
                querry.xymc = xymc;
                querry.ccode = ccode;

                querry.dateRange = dateRange;
                querry.status = status;



                (IEnumerable<dynamic>, int) SelectTable = await ProHeTongRule.GetHTBGXYList(querry, await GetDepId());//GetUserId()

                List<string> list = new List<string>();
                foreach (dynamic item in SelectTable.Item1)
                {
                    //这里是id
                    string id = item.id;
                    list.Add(id);
                }

                //审批流
                _logger.Debug(list.ToJson());
                List<JavaApi.SPSDataItem> spitems = await JavaApi.GetSPStatusJavaAPI(formCode, GetUserAccount(), list, await GetICApiInfo());
                _logger.Debug(spitems.ToJson());

                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.id;
                    var spstatus = spitems.Where(ii => ii.businessId == id).FirstOrDefault();

                    item.panguData = GetPanGudData(spstatus, item.spstatus);
                }



                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;
                return Success(pa);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 合同变更列表
        /// </summary>
        /// <param name="htid"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetHTBGXYListByhtid(string htid)
        {
            try
            {
                var SelectTable = await ProHeTongRule.GetHTBGXYListByhtid(htid);

                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 单条合同变更协议信息
        /// </summary>
        /// <param name="xid"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetHTBGXYByid(string xid)
        {
            try
            {
                var SelectTable = await ProHeTongRule.GetHTBGXYByid(xid);

                foreach (var item in SelectTable)
                {
                    string strhtid = item.htid;
                    var vhtxx = (await ProHeTongRule.GetHTByIdSig(strhtid));
                    item.htxx = vhtxx;
                }

                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        //[HttpGet]
        //[AllowAnonymous]
        //public async Task<IActionResult> GetHTBGXYInfoByid(string xid)
        //{
        //    try
        //    {
        //        var SelectTable = await ProHeTongRule.GetHTBGXYxmByid(xid);

        //        return Success(SelectTable);
        //    }
        //    catch (Exception ex)
        //    {
        //        return Fail(ex.Message);
        //    }
        //}

        protected async Task<dynamic> GetXYBM(string htid)
        {
            string strhtid = htid;

            string zjxz = "";
            string bid = "";

            string strsql = @"select htlx,buildunit,zjly,departid,(case when REPLACE(ISNULL(zjly,''),'财政','') = ISNULL(zjly,'') then '0' else '1' end)zid
 from CProContract 
left join CProManageLX on CProContract.dxid = CProManageLX.id
left join CProManage on CProManageLX.xmid = CProManage.id
where CProContract.id = '" + strhtid + "'";

            DataTable dts = await TranstionRule.ProcessSql(strsql);
            for (int i = 0; i < dts.Rows.Count; i++)
            {
                zjxz = dts.Rows[i]["zid"].ToString() == "1" ? "CZ" : "JY";
                bid = dts.Rows[i]["departid"].ToString();
            }

            string bname = "";
            var dwinfo = await GetDepInfoSig(bid, "project_permission");
            if (null != dwinfo)
                bname = dwinfo.mnemonicCode;

            dynamic DCcode = new ExpandoObject();
            DCcode.zcode = zjxz;//资金来源
            //DCcode.tcode = tname;//项目类型code
            DCcode.bcode = bname;//建设单位code

            return DCcode;
        }


        /// <summary>
        /// 新增修改合同变更
        /// </summary>
        /// <param name="htbgjson"></param>
        /// <param name="strlx"></param>
        /// <returns></returns>
        [HttpPost]
        //[AllowAnonymous]
        public async Task<IActionResult> InsertCProConBGXY(dynamic htbgjson)//string strlx = "xxx"
        {

            string strope = "add";
            CProConBGxy htbg = new CProConBGxy();


            //添加附件上传
            FileUploadent filecodes = new FileUploadent();
            try
            {
                JObject job = (JObject)htbgjson;

                //获取方法
                strope = htbgjson.ope ?? "";
                strope = strope.ToLower();

                //获取实体类 这样复杂类型不用定义实体类
                htbg = job["htbg"].ToObject<CProConBGxy>();


                //接收附件列表
                if (null != job["apiargs"])
                    filecodes = job["apiargs"].ToObject<FileUploadent>();


                if (strope != "add" && strope != "edit" && strope != "approved" && strope != "submit")
                {
                    return Fail("参数ope 不合法");
                }

            }
            catch (Exception ex)
            {
                return Fail("参数转换出错：" + ex.Message);
            }


            try
            {
                string strlsope = strope;
                if (strope == "submit")
                {
                    if (string.IsNullOrEmpty(htbg.id))//完成新增
                    {
                        strope = "add";
                    }
                    else
                    {
                        CProConBGxy jhe = await TranstionRule.FindEntityByKey<CProConBGxy>(htbg.id);
                        if (null == jhe)
                        {
                            strope = "add";
                        }
                        else
                        {
                            strope = "edit";
                        }
                    }
                    htbg.status = BaseEditPower.GetSPEnumValue("待审核");
                }

                if (strope == "add")
                {
                    if (string.IsNullOrEmpty(htbg.htid))
                    {
                        return Fail("变更关联的合同id不能为空");
                    }

                    //重新赋值一个新id
                    htbg.id = CommonHelper.GetUniqueId().ToString();

                    #region 生成变更编码

                    dynamic DCcode = await GetXYBM(htbg.htid);

                    htbg.xybm = await JavaApi.BusinessBMJavaAPI(BaseEditPower.listTableName[BaseEditPower.TableName.变更协议.ToString()], Newtonsoft.Json.JsonConvert.SerializeObject(DCcode), await GetICApiInfo());

                    #endregion

                    htbg.createuser = GetUserName();
                    htbg.createdate = DateTime.Now;

                    if (strlsope != "submit")
                        htbg.status = BaseEditPower.GetSPEnumValue("待提交");

                    //这里先绑定附件
                    await JavaApi.UploadFileJavaAPI(htbg.id, filecodes, await GetICApiInfo());


                    bool bsp = true;
                    if (strlsope == "submit")
                    {
                        bsp = false;

                        var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.变更协议.ToString(), htbg.id, htbg.htid);

                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = htbg.xybm, amount = htbg.xyje?.ToString(), content = "[变更协议]" + htbg.xymc, deptName = GetUserDeptName() };

                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.变更协议.ToString(), htbg.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(htbgjson), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);
                        //bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        //if (!bsp)
                        string strInstanceId = await JavaApi.startInstanceJavaAPIStr(spl, await GetICApiInfo());
                        htbg.spl = strInstanceId;
                        if (strInstanceId.StartsWith("err"))
                        {
                            return Fail("提交失败，启动工作流异常");
                        }
                    }

                    //新增投资计划
                    await ProHeTongRule.InsertHTBGXY(htbg, "add");
                }
                else if (strope == "edit")
                {
                    if (string.IsNullOrEmpty(htbg.id))
                    {
                        return Fail("需要修改的变更id不能为空");
                    }
                    if (string.IsNullOrEmpty(htbg.htid))
                    {
                        return Fail("变更关联的合同id不能为空");
                    }

                    //这里先绑定附件
                    await JavaApi.UploadFileJavaAPI(htbg.id, filecodes, await GetICApiInfo());

                    bool bsp = true;
                    if (strlsope == "submit")
                    {
                        bsp = false;

                        CProConBGxy jhe = await TranstionRule.FindEntityByKey<CProConBGxy>(htbg.id);
                        if (null == jhe)
                        {
                            return Fail("根据id未检索到变更协议信息");
                        }

                        var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.变更协议.ToString(), htbg.id, htbg.htid);

                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = jhe.xybm, amount = htbg.xyje?.ToString(), content = "[变更协议]" + htbg.xymc, deptName = GetUserDeptName() };

                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.变更协议.ToString(), htbg.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(htbgjson), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);
                        //bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        //if (!bsp)
                        string strInstanceId = await JavaApi.startInstanceJavaAPIStr(spl, await GetICApiInfo());
                        htbg.spl = strInstanceId;
                        if (strInstanceId.StartsWith("err"))
                        {
                            return Fail("提交失败，启动工作流异常");
                        }
                    }

                    //新增投资计划
                    await ProHeTongRule.InsertHTBGXY(htbg, "edit");
                }


                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail("响应失败:" + ex.Message);
            }
        }

        ///// <summary>
        ///// 修改合同变更
        ///// </summary>
        ///// <param name="htbg"></param>
        ///// <param name="strlx"></param>
        ///// <returns></returns>
        //[HttpPost]
        //[AllowAnonymous]
        //public async Task<IActionResult> InsertCProConBGXY(CProConBGxy htbg, string strlx = "xxx")//
        //{
        //    try
        //    {
        //        string strope = strlx.ToLower();
        //        if (strope != "add" && strope != "edit")
        //        {
        //            return Fail("strlx参数错误");
        //        }

        //        if (strope == "add")
        //        {
        //            if (string.IsNullOrEmpty(htbg.htid))
        //            {
        //                return Fail("变更关联的合同id不能为空");
        //            }

        //            //重新赋值一个新id
        //            htbg.id = CommonHelper.GetUniqueId().ToString();
        //            htbg.createuser = GetUserId();

        //            //新增投资计划
        //            await ProHeTongRule.InsertHTBGXY(htbg, "add");


        //        }
        //        else if (strope == "edit")
        //        {
        //            if (string.IsNullOrEmpty(htbg.id))
        //            {
        //                return Fail("需要修改的变更id不能为空");
        //            }
        //            if (string.IsNullOrEmpty(htbg.htid))
        //            {
        //                return Fail("变更关联的合同id不能为空");
        //            }


        //            //新增投资计划
        //            await ProHeTongRule.InsertHTBGXY(htbg, "edit");
        //        }


        //        return Success("成功");
        //    }
        //    catch (Exception ex)
        //    {
        //        return Fail("响应失败:" + ex.Message);
        //    }
        //}

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> DeleteCProConBGXYMulti(Root ids)//
        {
            try
            {
                foreach (BaseDeleteMulti idm in ids.ids)
                {
                    if (string.IsNullOrEmpty(idm.id))
                    {
                        return Fail("需要删除的变更编号不能为空");
                    }

                    //if (!await BaseEditPower.GetEditPower(idm.id, BaseEditPower.TableName.合同变更))
                    //{
                    //    //throw new Exception("请确认数据权限");
                    //    return Fail("响应失败:请确认数据权限");
                    //}
                }
            }
            catch (Exception ex)
            {
                return Fail("出错：" + ex.Message);
            }


            try
            {
                //新增投资计划
                if (await ProHeTongRule.DeleteHTBGXY(ids))
                {
                    return Success("成功");
                }
                else
                {
                    return Fail("影响行数为0");
                }

            }
            catch (Exception ex)
            {
                return Fail("响应失败:" + ex.Message);
            }
        }

        #endregion

        #region 变更设计

        /// <summary>
        /// 项目变更列表
        /// </summary>
        /// <param name="xmmc"></param>
        /// <param name="jsdw"></param>
        /// <param name="begindate"></param>
        /// <param name="enddate"></param>
        /// <param name="current"></param>
        /// <param name="size"></param>
        /// <param name="sort"></param>
        /// <param name="column"></param>
        /// <returns></returns>
        [HttpGet]
        //[Authorize(Policy = "TestPolicy")]
        //[AllowAnonymous]
        //bgmc   bglx
        public async Task<IActionResult> GetHTBGDesList(string formCode, string xmmc, string jsdw, string status, string bgmc, string bgzt, DateTime? begindate, DateTime? enddate, string current = "1", string size = "20", string sort = "desc", string column = "id")
        {
            try
            {
                CProConBGsjQuerry querry = new CProConBGsjQuerry();
                //基础属性
                querry.size = CommonHelper.ParseInt(size);
                querry.current = CommonHelper.ParseInt(current);
                querry.sort = sort;
                querry.column = column;

                querry.bgmc = bgmc;
                querry.bgzt = bgzt;

                querry.Xmmc = xmmc;
                querry.Jsdw = jsdw;
                querry.Status = status;
                querry.Begindate = begindate;
                querry.Enddate = enddate;


                (IEnumerable<dynamic>, int) SelectTable = await ProHeTongRule.GetHTBGDesignList(querry, await GetDepId());//GetUserId()

                List<string> list = new List<string>();
                foreach (dynamic item in SelectTable.Item1)
                {
                    //这里是id
                    string id = item.id;
                    list.Add(id);
                }

                //审批流
                _logger.Debug(list.ToJson());
                List<JavaApi.SPSDataItem> spitems = await JavaApi.GetSPStatusJavaAPI(formCode, GetUserAccount(), list, await GetICApiInfo());
                _logger.Debug(spitems.ToJson());

                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.id;
                    var spstatus = spitems.Where(ii => ii.businessId == id).FirstOrDefault();

                    item.panguData = GetPanGudData(spstatus, item.spstatus);

                    //if (null != spstatus)
                    //    item.panguData = GetPanGudData(spstatus, item.spstatus);
                    //else
                    //    item.panguData = new JavaApi.panguData() { reviewStatus = item.spstatus };
                }



                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;
                return Success(pa);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 合同变更列表
        /// </summary>
        /// <param name="htid"></param>
        /// <returns></returns>
        [HttpGet]
        //[AllowAnonymous]
        public async Task<IActionResult> GetHTBGDesListByhtid(string htid)
        {
            try
            {
                var SelectTable = await ProHeTongRule.GetHTBGDesignListByhtid(htid);

                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 合同变更列表 返回已审核
        /// </summary>
        /// <param name="htid"></param>
        /// <returns></returns>
        [HttpGet]
        //[AllowAnonymous]
        public async Task<IActionResult> GetHTBGDesListByhtidAudited(string htid)
        {
            try
            {
                var SelectTable = await ProHeTongRule.GetHTBGDesignListByhtidAudited(htid);

                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }


        /// <summary>
        /// 单条合同变更
        /// </summary>
        /// <param name="bgid"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetHTBGDesById(string bgid)
        {
            try
            {
                var SelectTable = await ProHeTongRule.GetHTBGDesignByid(bgid);
                //if (null != SelectTable)
                //{
                //    SelectTable.des
                //}
                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        [HttpPost]
        [AllowAnonymous]
        public IActionResult InsertCProConBGDes1(CProConBGSJ htbgjson)//, string strlx = "xxx"
        {
            return Success("");
        }

        /// <summary>
        /// 修改合同变更
        /// </summary>
        /// <param name="htbgjson"></param>
        /// <param name="strlx"></param>
        /// <returns></returns>
        [HttpPost]
        //[AllowAnonymous]
        public async Task<IActionResult> InsertCProConBGDes(dynamic htbgjson)//, string strlx = "xxx"
        {
            string strope = "add";
            CProConBGSJ htbg = new CProConBGSJ();

            //添加附件上传
            FileUploadent filecodes = new FileUploadent();
            try
            {
                JObject job = (JObject)htbgjson;

                //获取方法
                strope = htbgjson.ope ?? "";
                strope = strope.ToLower();

                //获取实体类 这样复杂类型不用定义实体类
                htbg = job["htbg"].ToObject<CProConBGSJ>();

                //if (null != job["tzxmids"])
                //    tzxmids = job["tzxmids"].ToObject<List<CProManageTZXM>>();

                //接收附件列表
                if (null != job["apiargs"])
                    filecodes = job["apiargs"].ToObject<FileUploadent>();


                if (strope != "add" && strope != "edit" && strope != "approved" && strope != "submit")
                {
                    return Fail("参数ope 不合法");
                }

            }
            catch (Exception ex)
            {
                return Fail("参数转换出错：" + ex.Message);
            }

            try
            {

                string strlsope = strope;
                if (strope == "submit")
                {
                    if (string.IsNullOrEmpty(htbg.id))//完成新增
                    {
                        strope = "add";
                    }
                    else
                    {
                        CProConBGSJ jhe = await TranstionRule.FindEntityByKey<CProConBGSJ>(htbg.id);
                        if (null == jhe)
                        {
                            strope = "add";
                        }
                        else
                        {
                            strope = "edit";
                        }
                    }
                    htbg.status = BaseEditPower.GetSPEnumValue("待审核");
                }

                if (strope == "add")
                {
                    if (string.IsNullOrEmpty(htbg.htid))
                    {
                        return Fail("变更关联的合同id不能为空");
                    }
                    //if (htbg.bgje == 0)
                    //{
                    //    return Fail("变更金额不能为空或零");
                    //}

                    //新增合同变更编码
                    htbg.bgbm = await JavaApi.BusinessBMJavaAPI(BaseEditPower.listTableName[BaseEditPower.TableName.设计变更.ToString()], Newtonsoft.Json.JsonConvert.SerializeObject(htbgjson), await GetICApiInfo());
                    //await BusinessRule.Assets.CreateZCDM("XM", "SJBG");

                    //重新赋值一个新id
                    htbg.id = CommonHelper.GetUniqueId().ToString();
                    htbg.createuser = GetUserId();


                    //填报时间
                    htbg.tbsj = DateTime.Now;


                    if (strlsope != "submit")
                        htbg.status = BaseEditPower.GetSPEnumValue("待提交");

                    //这里先绑定附件
                    await JavaApi.UploadFileJavaAPI(htbg.id, filecodes, await GetICApiInfo());

                    bool bsp = true;
                    if (strlsope == "submit")
                    {
                        bsp = false;

                        dynamic _dynamic = new ExpandoObject();
                        _dynamic.bgje = htbg.bgje;
                        //_dynamic.bl = htbg.ljbgbl;

                        var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.设计变更.ToString(), htbg.id);

                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = htbg.bgbm, amount = htbg.bgje?.ToString(), content = "[设计变更]" + htbg.bgmc, deptName = GetUserDeptName() };

                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.设计变更.ToString(), htbg.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(_dynamic), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);
                        //bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        //if (!bsp)
                        string strInstanceId = await JavaApi.startInstanceJavaAPIStr(spl, await GetICApiInfo());
                        htbg.spl = strInstanceId;
                        if (strInstanceId.StartsWith("err"))
                        {
                            return Fail("提交失败，启动工作流异常");
                        }
                    }

                    //新增投资计划
                    await ProHeTongRule.InsertHTBGDesign(htbg, "add");


                }
                else if (strope == "edit")
                {
                    if (string.IsNullOrEmpty(htbg.id))
                    {
                        return Fail("需要修改的变更id不能为空");
                    }
                    if (string.IsNullOrEmpty(htbg.htid))
                    {
                        return Fail("变更关联的合同id不能为空");
                    }
                    //if (htbg.sqje == 0)
                    //{
                    //    return Fail("变更金额不能为空或零");
                    //}

                    //这里先绑定附件
                    await JavaApi.UploadFileJavaAPI(htbg.id, filecodes, await GetICApiInfo());

                    bool bsp = true;
                    if (strlsope == "submit")
                    {
                        bsp = false;

                        CProConBGSJ jhe = await TranstionRule.FindEntityByKey<CProConBGSJ>(htbg.id);
                        if (null == jhe)
                        {
                            return Fail("根据id未检索到变更信息");
                        }

                        dynamic _dynamic = new ExpandoObject();
                        _dynamic.bgje = htbg.bgje;

                        var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.设计变更.ToString(), htbg.id);

                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = jhe.bgbm, amount = htbg.bgje?.ToString(), content = "[设计变更]" + htbg.bgmc, deptName = GetUserDeptName() };
                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.设计变更.ToString(), htbg.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(_dynamic), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);
                        //bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        //if (!bsp)
                        string strInstanceId = await JavaApi.startInstanceJavaAPIStr(spl, await GetICApiInfo());
                        htbg.spl = strInstanceId;
                        if (strInstanceId.StartsWith("err"))
                        {
                            return Fail("提交失败，启动工作流异常");
                        }
                    }

                    //新增投资计划
                    await ProHeTongRule.InsertHTBGDesign(htbg, "edit");
                }
                //else if (strope == "approved")
                //{
                //    if (string.IsNullOrEmpty(htbg.id))
                //    {
                //        return Fail("合同变更编号不能为空");
                //    }
                //    if (htbg.bgsdje == 0)
                //    {
                //        return Fail("变更审定金额不能为空或零");
                //    }

                //    //获取概算的当前状态
                //    CProConBG htBGe = await TranstionRule.FindEntityByKey<CProConBG>(htbg.id);
                //    string strstatus = "";
                //    if (null != htBGe)
                //    {
                //        strstatus = htBGe.status ?? "";
                //    }

                //    if (strstatus == "2")
                //    {
                //        //这里先绑定附件
                //        await JavaApi.UploadFileJavaAPI(htbg.id, filecodes, await GetICApiInfo());

                //        //新增投资计划
                //        await ProHeTongRule.InsertHTBG(htbg, "edit");
                //    }
                //    else
                //    {
                //        return Fail("数据状态为" + strstatus + ",未审核完成");
                //    }
                //}


                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail("响应失败:" + ex.Message);
            }
        }

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> DeleteCProConBGDesMulti(Root ids)//
        {
            try
            {
                foreach (BaseDeleteMulti idm in ids.ids)
                {
                    if (string.IsNullOrEmpty(idm.id))
                    {
                        return Fail("需要删除的变更编号不能为空");
                    }

                    if (!await BaseEditPower.GetEditPower(idm.id, BaseEditPower.TableName.设计变更))
                    {
                        //throw new Exception("请确认数据权限");
                        return Fail("响应失败:请确认数据权限");
                    }
                }
            }
            catch (Exception ex)
            {
                return Fail("出错：" + ex.Message);
            }


            try
            {
                //新增投资计划
                if (await ProHeTongRule.DeleteHTBGDesign(ids))
                {
                    return Success("成功");
                }
                else
                {
                    return Fail("影响行数为0");
                }

            }
            catch (Exception ex)
            {
                return Fail("响应失败:" + ex.Message);
            }
        }

        #endregion

        #region 合同保证金

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> GetHTReleasedeposit(dynamic bzjjson)
        {
            string strope = "add";
            CProConBZJ bzj = new CProConBZJ();

            //附件
            FileUploadent filecodes = new FileUploadent();
            try
            {
                JObject job = (JObject)bzjjson;

                //获取方法
                strope = bzjjson.ope;
                strope = strope.ToLower();

                //获取实体类 这样复杂类型不用定义实体类
                if (null != job["bzj"])
                    bzj = job["bzj"].ToObject<CProConBZJ>();

                //接收附件列表
                if (null != job["apiargs"])
                    filecodes = job["apiargs"].ToObject<FileUploadent>();

                if (strope != "add" && strope != "edit" && strope != "release" && strope != "confirm") //release confirm
                {
                    return Fail("参数ope 不合法");
                }

            }
            catch (Exception ex)
            {
                return Fail("参数转换出错：" + ex.Message);
            }


            try
            {
                if (string.IsNullOrEmpty(bzj.id))
                {
                    return Fail("合同保证金id不能为空");
                }
                if (bzj.thje == 0)
                {
                    return Fail("保证金thje不能为空或零");
                }
                if (null == bzj.thrq)
                {
                    return Fail("保证金thrq不能为空");
                }

                bzj.htid = null;

                CProConBZJ jhe = await TranstionRule.FindEntity<CProConBZJ>(new { id = bzj.id });
                if (null != jhe)
                {

                    //这里先绑定附件
                    //await JavaApi.UploadFileJavaAPI(bzj.id, filecodes, await GetICApiInfo());
                    if (jhe.bzjje > bzj.thje)
                    {
                        //已退还
                        bzj.bzjzt = "部分退还";
                    }
                    else if (jhe.bzjje <= bzj.thje)
                    {
                        bzj.bzjzt = "已退还";
                    }


                    //if (strope == "confirm")
                    //    bzj.step = "confirm";
                    //if (strope == "release")
                    //    bzj.step = "release";

                    await ProHeTongRule.UpdateConBZJ(bzj);

                    return Success("成功");
                }
                else
                {
                    return Fail("根据id查找不到对应的保证金");
                }

            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 项目变更列表
        /// </summary>
        /// <param name="xmmc"></param>
        /// <param name="jsdw"></param>
        /// <param name="begindate"></param>
        /// <param name="enddate"></param>
        /// <param name="current"></param>
        /// <param name="size"></param>
        /// <param name="sort"></param>
        /// <param name="column"></param>
        /// <returns></returns>
        [HttpGet]
        //[AllowAnonymous]
        public async Task<IActionResult> GetHTBZJIndexList(string formCode, string xmmc, string htbm, string htmc, string htlx, string bhjeb, string bhjee, string bzjmc, string status, string current = "1", string size = "20", string sort = "desc", string column = "id")
        {
            try
            {

                // htbm,string htmc,string htlx,string bhje,

                CProConBZJQuerry querry = new CProConBZJQuerry();
                //基础属性
                querry.size = CommonHelper.ParseInt(size);
                querry.current = CommonHelper.ParseInt(current);
                querry.sort = sort;
                querry.column = column;

                querry.htbm = htbm;
                querry.htmc = htmc;
                querry.htlx = htlx;
                querry.bhjeb = bhjeb;
                querry.bhjee = bhjee;

                querry.bzjmc = bzjmc;
                //querry.bzjzt = bzjzt;

                querry.xmmc = xmmc;
                //querry.Jsdw = jsdw;
                querry.status = status;
                //querry.Begindate = begindate;
                //querry.Enddate = enddate;


                (IEnumerable<dynamic>, int) SelectTable = await ProHeTongRule.GetHTBZJIndexList(querry, await GetDepId());//GetUserId()

                List<string> list = new List<string>();
                foreach (dynamic item in SelectTable.Item1)
                {
                    //这里是id
                    string id = item.id;
                    list.Add(id);
                }

                //审批流
                _logger.Debug(list.ToJson());
                List<JavaApi.SPSDataItem> spitems = await JavaApi.GetSPStatusJavaAPI(formCode, GetUserAccount(), list, await GetICApiInfo());
                _logger.Debug(spitems.ToJson());

                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.id;
                    var spstatus = spitems.Where(ii => ii.businessId == id).FirstOrDefault();

                    item.panguData = GetPanGudData(spstatus, item.spstatus);

                    //if (null != spstatus)
                    //    item.panguData = GetPanGudData(spstatus, item.spstatus);
                    //else
                    //    item.panguData = new JavaApi.panguData() { reviewStatus = item.spstatus };
                }



                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;
                return Success(pa);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        [HttpGet]
        //[AllowAnonymous]
        //string xmmc, string htbm, string htmc, string htlx, string bhjeb,string bhjee, string bzjmc, string bzjzt, string status, string current = "1", string size = "20", string sort = "desc", string column = "id"
        public async Task<IActionResult> GetXZHTBZJIndexList([FromQuery] CProConBZJQuerry querry)
        {
            try
            {

                // htbm,string htmc,string htlx,string bhje,

                //CProConBZJQuerry querry = new CProConBZJQuerry();
                ////基础属性
                //querry.size = CommonHelper.ParseInt(size);
                //querry.current = CommonHelper.ParseInt(current);
                //querry.sort = sort;
                //querry.column = column;

                //querry.htbm = htbm;
                //querry.htmc = htmc;
                //querry.htlx = htlx;
                //querry.bhjeb = bhjeb;
                //querry.bhjee = bhjee;

                //querry.bzjmc = bzjmc;
                //querry.bzjzt = bzjzt;

                //querry.xmmc = xmmc;
                ////querry.Jsdw = jsdw;
                //querry.status = status;



                (IEnumerable<dynamic>, int) SelectTable = await ProHeTongRule.GetXZHTBZJIndexList(querry, await GetDepId());//GetUserId()


                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;
                return Success(pa);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 合同保证金列表
        /// </summary>
        /// <param name="htid"></param>
        /// <returns></returns>
        [HttpGet]
        //[AllowAnonymous]
        public async Task<IActionResult> GetHTBZJListByhtid(string htid)
        {
            try
            {
                var SelectTable = await ProHeTongRule.GetHTBZJListByhtid(htid);

                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }


        /// <summary>
        /// 单条合同保证金
        /// </summary>
        /// <param name="bzjid"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetHTBZJById(string bzjid)
        {
            try
            {
                var SelectTable = await ProHeTongRule.GetHTBZJByid(bzjid);

                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        [HttpPost]
        [AllowAnonymous]
        public IActionResult InsertCProConBZJ1(CProConBZJ htbzjjson)//, string strlx = "xxx"
        {
            return Success("");
        }

        /// <summary>
        /// 修改合同变更
        /// </summary>
        /// <param name="htbgjson"></param>
        /// <param name="strlx"></param>
        /// <returns></returns>
        [HttpPost]
        //[AllowAnonymous]
        public async Task<IActionResult> InsertCProConBZJ(dynamic htbzjjson)//, string strlx = "xxx"
        {
            string strope = "add";
            CProConBZJ htbzj = new CProConBZJ();

            //添加附件上传
            FileUploadent filecodes = new FileUploadent();
            try
            {
                JObject job = (JObject)htbzjjson;

                //获取方法
                strope = htbzjjson.ope ?? "";
                strope = strope.ToLower();

                //获取实体类 这样复杂类型不用定义实体类
                htbzj = job["htbzj"].ToObject<CProConBZJ>();

                //if (null != job["tzxmids"])
                //    tzxmids = job["tzxmids"].ToObject<List<CProManageTZXM>>();

                //接收附件列表
                if (null != job["apiargs"])
                    filecodes = job["apiargs"].ToObject<FileUploadent>();


                if (strope != "add" && strope != "edit" && strope != "approved" && strope != "submit")
                {
                    return Fail("参数ope 不合法");
                }

            }
            catch (Exception ex)
            {
                return Fail("参数转换出错：" + ex.Message);
            }

            try
            {

                string strlsope = strope;
                if (strope == "submit")
                {
                    if (string.IsNullOrEmpty(htbzj.id))//完成新增
                    {
                        strope = "add";
                    }
                    else
                    {
                        CProConBZJ jhe = await TranstionRule.FindEntityByKey<CProConBZJ>(htbzj.id);
                        if (null == jhe)
                        {
                            strope = "add";
                        }
                        else
                        {
                            strope = "edit";
                        }
                    }
                    htbzj.status = BaseEditPower.GetSPEnumValue("待审核");
                }

                if (strope == "add")
                {

                    //这里给1
                    htbzj.step = "1";

                    //退回时间
                    //htbzj.thrq = DateTime.Now;

                    //填报时间
                    if (string.IsNullOrEmpty(htbzj.sqrq?.ToString()))
                    {
                        htbzj.sqrq = DateTime.Now;
                    }
                    //htbzj.sqr = GetUserName();


                    if (strlsope != "submit")
                        htbzj.status = BaseEditPower.GetSPEnumValue("待提交");

                    //编码
                    htbzj.bm = await JavaApi.BusinessBMJavaAPI(BaseEditPower.listTableName[BaseEditPower.TableName.合同保证金.ToString()], Newtonsoft.Json.JsonConvert.SerializeObject(htbzjjson), await GetICApiInfo());

                    //如果fjid
                    CProConBZJ jhe = await TranstionRule.FindEntityByKey<CProConBZJ>(htbzj.id);
                    if (null == jhe)
                    {
                        return Fail("根据id未检索到保函信息");
                    }
                    if (string.IsNullOrEmpty(jhe.fjid))
                        htbzj.fjid = CommonHelper.GetUniqueId().ToString();

                    //这里先绑定附件
                    await JavaApi.UploadFileJavaAPI(htbzj.fjid, filecodes, await GetICApiInfo());

                    bool bsp = true;
                    if (strlsope == "submit")
                    {
                        bsp = false;

                        var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.合同保证金.ToString(), htbzj.htid, htbzj.id);

                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = htbzj.id, amount = htbzj.thje?.ToString(), content = "[保证金退还]" + htbzj.bzjname, deptName = GetUserDeptName() };

                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.合同保证金.ToString(), htbzj.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(htbzjjson), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);
                        //bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        //if (!bsp)
                        string strInstanceId = await JavaApi.startInstanceJavaAPIStr(spl, await GetICApiInfo());
                        htbzj.spl = strInstanceId;
                        if (strInstanceId.StartsWith("err"))
                        {
                            return Fail("提交失败，启动工作流异常");
                        }
                    }

                    //新增投资计划
                    await ProHeTongRule.InsertHTBZJ(htbzj, "edit");


                }
                else if (strope == "edit")
                {
                    if (string.IsNullOrEmpty(htbzj.id))
                    {
                        return Fail("需要修改的变更id不能为空");
                    }

                    htbzj.step = "1";

                    //如果fjid
                    CProConBZJ jhe = await TranstionRule.FindEntityByKey<CProConBZJ>(htbzj.id);
                    if (null == jhe)
                    {
                        return Fail("根据id未检索到保函信息");
                    }
                    if (string.IsNullOrEmpty(jhe.fjid))
                        htbzj.fjid = CommonHelper.GetUniqueId().ToString();


                    if (string.IsNullOrEmpty(htbzj.bm))
                        //编码
                        htbzj.bm = await JavaApi.BusinessBMJavaAPI(BaseEditPower.listTableName[BaseEditPower.TableName.合同保证金.ToString()], Newtonsoft.Json.JsonConvert.SerializeObject(htbzjjson), await GetICApiInfo());



                    //这里先绑定附件
                    await JavaApi.UploadFileJavaAPI(htbzj.fjid, filecodes, await GetICApiInfo());

                    bool bsp = true;
                    if (strlsope == "submit")
                    {
                        bsp = false;

                        //CProConBZJ jhe = await TranstionRule.FindEntityByKey<CProConBZJ>(htbzj.id);
                        //if (null == jhe)
                        //{
                        //    return Fail("根据id未检索到变更信息");
                        //}

                        var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.合同保证金.ToString(), htbzj.htid, htbzj.id);

                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = htbzj.id, amount = htbzj.thje?.ToString(), content = "[合同保证金]" + htbzj.bzjname, deptName = GetUserDeptName() };
                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.合同保证金.ToString(), htbzj.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(htbzjjson), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);
                        //bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        //if (!bsp)
                        string strInstanceId = await JavaApi.startInstanceJavaAPIStr(spl, await GetICApiInfo());
                        htbzj.spl = strInstanceId;
                        if (strInstanceId.StartsWith("err"))
                        {
                            return Fail("提交失败，启动工作流异常");
                        }
                    }

                    //新增投资计划
                    await ProHeTongRule.InsertHTBZJ(htbzj, "edit");
                }

                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail("响应失败:" + ex.Message);
            }
        }

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> DeleteCProConBZJMulti(Root ids)//
        {
            try
            {
                foreach (BaseDeleteMulti idm in ids.ids)
                {
                    if (string.IsNullOrEmpty(idm.id))
                    {
                        return Fail("需要删除的变更编号不能为空");
                    }

                    if (!await BaseEditPower.GetEditPower(idm.id, BaseEditPower.TableName.合同保证金))
                    {
                        //throw new Exception("请确认数据权限");
                        return Fail("响应失败:请确认数据权限");
                    }
                }
            }
            catch (Exception ex)
            {
                return Fail("出错：" + ex.Message);
            }


            try
            {
                //新增投资计划
                if (await ProHeTongRule.DeleteHTBZJTH(ids))
                {
                    return Success("成功");
                }
                else
                {
                    return Fail("影响行数为0");
                }

            }
            catch (Exception ex)
            {
                return Fail("响应失败:" + ex.Message);
            }
        }
        #endregion

    }
}
